//index.js
var util = require('../../utils/util.js')
var config = require('../../config')
var WxParse = require('../../wxParse/wxParse.js')

var app = getApp()

Page({
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,

    goodsDetail: {},
    hasMoreSelect: false,
    selectSize: "选择：",
    selectSizePrice: 0,
    totalPrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 1,
    buyNumMax: 100,

    propertyChildIds: "",
    propertyChildNames: "",
    shopCarInfo: [],
    shopType: "addShopCar",//购物类型，加入购物车或立即购买，默认为加入购物车
    selectedGoods: {},
    reputation: {},
    shopCarData: [],
    userid: app.globalData.userInfo.userid,
  },

  onLoad: function (options) {
    var that = this;
    var item=JSON.parse(options.item);
    that.setData({goodsDetail:item})

    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        // 分享成功
        console.log('onLoad success'+JSON.stringify(res))
      },
      fail: function (res) {
        // 分享失败
        console.log('onLoad fail'+JSON.stringify(res))
      }
    });

    //wx.request({
    //  url: config.service.couponDetail,
    //  data: {
    //    userid: that.data.userid,
    //    pid: item.id
    //  },
    //  success: function (res) {
    //    if (res.data.code == 0) {
    //        item.has_coupon = res.data.da.has_coupon;
    //        that.setData({goodsDetail:item})
    //    }
    //    console.log('success-'+JSON.stringify(res.data.data))
    //  }
    //});

    wx.request({
      url: config.service.productInfoHtml,
      data: {
        short: item.short,
        pid: item.id
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: function (res) {
        if (res.data.code == 0) {
          var article = res.data.data.introduction;
          WxParse.wxParse('article', 'html', article, that, 0)
        }
      }
    });


  },

  onMoreRatingTap: function (e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/more-rating/index?id=' + id
    })
  },
  onViewImgTap: function (e) {
    var currentImg = e.currentTarget.dataset.img
    var pics = e.currentTarget.dataset.pics
    wx.previewImage({
      current: currentImg,
      urls: pics
    })
  },
  goShopCar: function () {
    wx.switchTab({
      url: "/pages/shopcart/index"
    })
  },
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap()
  },
  tobuy: function () {
    this.setData({
      shopType: "tobuy"
    })
    this.bindGuiGeTap()
  },

  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function () {
    //this.labelItemTap()

    this.getSpecItems(this.data.goodsDetail.id)
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function () {
    if (this.data.selectedGoods.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.selectedGoods.buyNumber;
      currentNum--;
      var goods =  this.data.selectedGoods;
      goods.buyNumber = currentNum;
      this.setData({
        selectedGoods:goods,
        totalPrice:(this.data.selectedGoods.price * currentNum).toFixed(2)
      })
    }
  },
  numJiaTap: function () {
    if (this.data.selectedGoods.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.selectedGoods.buyNumber;
      currentNum++;
      var goods =  this.data.selectedGoods;
      goods.buyNumber = currentNum;
      this.setData({
        selectedGoods:goods,
        totalPrice:(this.data.selectedGoods.price * currentNum).toFixed(2)
      })
    }
  },

  /**
  * 加入购物车
  */
  addShopCar: function () {
    var _this = this
    var userInfoStorage = wx.getStorageSync('userInfo');

    if (!util.isNUll(userInfoStorage)){
      app.globalData.userInfo = userInfoStorage
      wx.request({
        url: config.service.cartAdd,
        data: {
          unionid: app.globalData.userInfo.unionId,
          id: this.data.selectedGoods.id,
          number: this.data.selectedGoods.buyNumber,
          goods_id: this.data.selectedGoods.goods_id,
          name: this.data.selectedGoods.name,
          price: this.data.selectedGoods.price,
          pic:this.data.goodsDetail.pic,
        },
        success: function (res) {
          if (res.data.code == 0) {
            _this.setData({
              hideShopPopup: true
            })
            wx.showToast({
              title: '加入购物车成功',
              icon: 'success',
              duration: 2000
            })

            // 获取购物车数据
            var shopCarInfo = wx.getStorageSync('shopCarInfo')
            // var list = shopCarInfo.shopList
            if (shopCarInfo && shopCarInfo.shopList) {
              _this.setData({
                shopCarInfo: shopCarInfo
              })
            }
            //组建购物车
            //var shopCarInfo = _this.bulidShopCarInfo()
            //// 写入本地存储
            //wx.setStorage({
            //  key: "shopCarInfo",
            //  data: shopCarInfo
            //})
              _this.requsetShopCarInfo()
          }
        }
      })
    } else {
      wx.showModal({
        title: '登录提示',
        content: '登录后再来看吧',
        success(res) {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/user/index',
          })
        }
      }
    })
    }
  },

  // 立即购买
  buyNow: function () {
    if (this.data.selectedGoods.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return
    }

    if (app.globalData.userInfo) {
      //wx.request({
      //  url: config.service.generateOrder,
      //  data: {
      //    id: this.data.selectedGoods.id,
      //    num: this.data.selectedGoods.buyNumber,
      //    uid: app.globalData.userInfo.unionId,
      //    gtype_id: this.data.selectedGoods.gtype_id,
      //    goods_id: this.data.selectedGoods.goods_id,
      //    goods_name: this.data.selectedGoods.name,
      //    goods_att: this.data.selectedGoods.goods_att,
      //    amount: this.data.selectedGoods.price
      //
      //  },
      //  success: (res) => {
      //
      //  }
      //})

      this.setData({
        hideShopPopup: true
      })
      //组建立即购买信息
      var buyNowInfo = this.buliduBuyNowInfo()
      // 写入本地存储
      wx.setStorage({
        key: "buyNowInfo",
        data: buyNowInfo
      })
      this.closePopupTap()
      wx.navigateTo({
        url: "/pages/to-pay-order/index?orderType=buyNow"
      })


    } else {
      wx.showModal({
        title: '登录提示',
        content: '登录后再来看看吧',
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/user/index',
            })
          }
        }
      })
    }
  },
  requsetShopCarInfo: function () {
    wx.request({
          url: config.service.cartList,
          data: {
            userid: this.data.userid,

          },
          success: (res) => {
        var shopCarInfo = {}
        shopCarInfo.shopList = res.data.data
      wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })

  }
  })},
    // 组建购物车信息
  bulidShopCarInfo: function () {
    // 加入购物车
    var shopCarMap = {}

    shopCarMap.shopList = {
      active: false,
      userid: this.data.userid,
      goods_id: this.data.selectedGoods.id,
      number: this.data.selectedGoods.buyNumber,
      name: this.data.selectedGoods.name,
      pic: this.data.goodsDetail.pic,
      price: this.data.selectedGoods.price,
    }
    var shopCarInfo = this.data.shopCarInfo

    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = []
    }
    var hasSameGoodsIndex = -1
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i]
      if (tmpShopCarMap.goods_id == shopCarMap.shopList.goods_id) {
        hasSameGoodsIndex = i
        shopCarMap.shopList.active = tmpShopCarMap.active
        shopCarMap.shopList.goods_num = parseInt(shopCarMap.shopList.goods_num) + parseInt(tmpShopCarMap.goods_num)
        break
      }
    }
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap.shopList)
    } else {
      shopCarInfo.shopList.push(shopCarMap.shopList)
    }
    return shopCarInfo
  },

  // 组建立即购买信息
  buliduBuyNowInfo: function () {
    var shopCarMap = {}
    var price = this.data.selectedGoods.price;
    var dicount =this.data.goodsDetail.discount;
    let RMB = this.data.selectedGoods.has_coupon==1?price/dicount:price;
    shopCarMap.shopList = [{
      userid: this.data.userid,
      goods_id: this.data.selectedGoods.id,
      number: this.data.selectedGoods.buyNumber,
      name: this.data.selectedGoods.name,
      pic: this.data.goodsDetail.pic,
      price:parseInt(RMB).toFixed(0),
      discount:dicount,
      has_coupon:this.data.goodsDetail.has_coupon,
    }]
    var buyNowInfo = shopCarMap
    return buyNowInfo;
  },
  /**
   * 选择商品规格
   */
  getSpecItems: function ($id) {
    this.http(config.service.productSpec,$id,this.bannerData)
  },
  http: function (url,id, callback) {

    wx.request({
      url: url,
      data: {
        id: id
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        callback(res.data.data)
        console.log(res.data.data);
      },
        fail: function(e) {
            util.showModel('失败')
        }
    })
  },
    bannerData: function (data) {
      data[0].active = 'active';
      data[0].buyNumber = '1';
      this.setData({
          shopCarData: data,
          selectedGoods:data[0]
        })
    },
  productItemTap:function(e){
    var index = e.currentTarget.dataset.item
    var newData = this.data.shopCarData;
    for(var i = 0;i<newData.length;i++){
      newData[i].active = '';
      newData[i].buyNumber = '1';
    }
    newData[index].active = 'active';

    this.setData({
      shopCarData:newData,
      selectedGoods:newData[index]
    })
  },

  onShareAppMessage: function () {
    var that = this;
    return {
      title: this.data.goodsDetail.title,
      path: 'pages/share-link/index?pid=' + this.data.goodsDetail.id,
      success: function (res) {
        var shareTickets =null

        if (!util.isNUll(res.shareTickets)) {
            shareTickets = res.shareTickets[0];
        }
        // console.log
        wx.getShareInfo({
          shareTicket: shareTickets,
          success: function (res) {
            if (!util.isNUll(shareTickets)){
                that.getCoupon();
          }else{
              console.log('-success- 个人用户');
            }
          },
          fail: function (res) {
            //console.log('fail'+JSON.stringify(res))
            that.storeShare(that.data.goodsDetail.id,that.data.userid);
          },
          complete: function (res) { console.log('complete'+JSON.stringify(res)) }
        })
      },
      fail: function (res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  storeShare:function(pid,userid) {
    wx.request({
      url: config.service.userShare,
      data: {
        pid:pid,
        userid: this.data.userid,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(JSON.stringify(res));
      }
    })
  },
  getCoupon: function (e) {
    var that = this;
    wx.request({
      url: config.service.couponAdd,
      data: {
        pid: that.data.goodsDetail.id,
        userid: that.data.userid,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {

        var data = that.data.goodsDetail;
        data.has_coupon = 1;
        that.setData({
          goodsDetail: data
        });
        wx.showToast({
          title: '领取成功',
          icon: 'success',
          duration: 2000
        })

        setTimeout(function () {
          wx.hideToast();
        }, 1000);
      }
    })
  },
    goHome:function () {
      wx.switchTab({
        url: '../home/index',
      });
  },
  submit: function (e) {

    this.getAccessToken(e.detail.formId);
  },
  getAccessToken: function (formId) {
    var that = this;
    wx.request({
      url: config.service.accessToken+'?grant_type=client_credential&appid=wxda7ca4eac0e90af7&secret=e229652cfc8c8b91af944cdca5c59f65',
      success: function (res) {
        app.globalData.access_token = res.data.access_token;
        that.sendMessage(app.globalData.access_token,formId);
      }
    })
  },
  sendMessage: function (access_token,formId) {

    var that = this;
    wx.request({
      url: config.service.sendMessage+'?access_token='+access_token,
      data: {
        touser: app.globalData.userInfo.openid,
        template_id: "lcHl1PebOsVW4tiTvsb649acTf7Q6sFWsunMNu4AIMQ",
        page: "pages/home/index",
        form_id: formId,
        data: {
          keyword1:{
            value: that.data.goodsDetail.name,
            color: '#173177'
          },
          keyword2:{
            value: that.formatTime(new Date()),
            color: '#173177'
          },
          keyword3:{
            value: that.data.goodsDetail.discount*10+'折折扣',
            color: '#173177'
          }
        },
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(JSON.stringify(res));
      }
    })
  },
  formatTime:function(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()

    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    return [year, month, day].join('-') + ' ' + [hour, minute].join(':')
  },
  })
